package com.awa.usercenter.config;

import com.awa.usercenter.model.code.SmsAuthenticationToken;
import com.awa.usercenter.model.domain.User;
import com.awa.usercenter.service.impl.sysUserDetailsService;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
@Service
public class SmsAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    sysUserDetailsService sysUserDetailsService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        Object principal = authentication.getPrincipal();// 获取凭证也就是用户的手机号
        User loginUser = new User();
        loginUser.setPhone(String.valueOf(principal));
        String inputCode = (String) authentication.getCredentials(); // 获取输入的验证码
        // 1. 检验Redis手机号的验证码
        String redisCode = redisTemplate.opsForValue().get(loginUser.getPhone());
        System.out.println(redisCode);
        if (StringUtils.isEmpty(redisCode)) {
            throw new BadCredentialsException("验证码已经过期或尚未发送，请重新发送验证码");
        }
        if (!inputCode.equals(redisCode)) {
            throw new BadCredentialsException("输入的验证码不正确，请重新输入");
        }
        redisTemplate.delete(loginUser.getPhone());// 删除验证码
        // 2. 根据手机号查询用户信息
        UserDetails userDetails = sysUserDetailsService.loadUserByUsername(loginUser.getPhone());
        if (userDetails == null) {
            throw new InternalAuthenticationServiceException("phone用户不存在，请注册");
        }
        // 3. 创建已认证对象
        return new SmsAuthenticationToken(loginUser, userDetails, userDetails.getAuthorities());
    }


    @Override
    public boolean supports(Class<?> aClass) {
        // 当 SmsAuthenticationToken 认证时，匹配该类
        return SmsAuthenticationToken.class.isAssignableFrom(aClass);
    }

    public void setUserDetailsService(sysUserDetailsService sysUserDetailsService) {
        this.sysUserDetailsService = sysUserDetailsService;
    }
}